<?php

namespace myshop\login\controller;

use app\BaseController;
use longhu\library\WechatService;
use longhu\MyResponse;
use longhu\services\easywechat\client\MyToken;
use longhu\services\easywechat\client\WechatClient;
use longhu\services\easywechat\listener\MessageListener;
use think\annotation\route\Route;
use think\facade\Log;
use think\response\Json;

class WechatAuth extends BaseController
{
    /**
     * 微信服务端验证
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    #[Route('GET|POST','wechat/validate')]
    public function wechatValidate()
    {
        $server = WechatService::create()->getApplication()->getServer();
        //if()
        //$user = WechatService::create()->getApplication()->getOAuth()->;
        $server->with(MessageListener::class);
//        $server->addEventListener('subscribe', function($message, \Closure $next) {
//            return '感谢您关注 惠多葆!';
//        });
        return $server->serve();
    }



    /***微信授权**/
    #[Route('GET|POST','wechat/auth')]
    public function wechatAuth()
    {
        $server = WechatService::create()->getApplication();
        $config = $server->getConfig();
        $oauth = WechatService::create()->getApplication()->getOAuth();
        if(empty(cache('wechat_user'))){
            //$_SESSION['intend_url'] = 'user/profile';
            //生成完整的授权URL
            $redirectUrl = $oauth->scopes(['snsapi_base'])->withState(base64_encode('wechat/auth'))->redirect();
            Log::info($redirectUrl);
            return redirect($redirectUrl);
          //  header("Location: {$redirectUrl}");
        }else{
            cache('wechat_user',null);
        }
    }


    /**
     * @return void
     */
    #[Route('GET|POST','wechat/redirect')]
    public function wechatAuthRedirect()
    {
        $oauth = WechatService::create()->getApplication()->getOAuth();
        $code = request()->param('code','');
        $state = request()->param('state','');
        // Log::info('state:'.base64_decode($state));
//        cache('wechat_user',$user->toArray());
        $user = $oauth->userFromCode($code);
        $userInfo = $user->getRaw();
        $accessToken = $user->getAccessToken();
        cache('wechat_user',$user->toArray());
        cache('wechat_user_token',$accessToken);
        // Log::write(json_encode($user->toArray()).'#######====>'.$accessToken);
        $targetUrl =  (string) \think\facade\Route::buildUrl('wechat/auth') ->suffix('')->domain(true);
        //dump($targetUrl);exit;
        return redirect($targetUrl);
    }

    #[Route('GET','wechat/userInfo')]
    public function getWechatUserInfo()
    {
        $cli  = WechatService::create()->getApplication()->getClient();
        $token = '80_bZD6eyHkuonFAmRykR7KzjoPd0n0QW17GkqROpVWdRJAlRxB7pimxRkCdCR6jDSj8wC7rhX5fIELgv919LQKEgUee_gv9Bm1Rapg_PtyisE';
        $cli = $cli->withAccessToken(new MyToken());
        $user = $cli->get('/sns/userinfo',[
            'openid'=>'oyjMl5w4bKuNvWrINpSFZtusErxM',
            'access_token'=>$token
        ]);
        dump($user->getInfo());exit;
    }

    /****
     * 小程序授权
     * @return Json
     */
    #[Route('POST','wechat/mpAuth')]
    public function mpAuth()
    {
        $code = request()->param('jsCode','');
        if(empty($code)){
            return MyResponse::fail('code不能为空');
        }
        $client = WechatClient::create();
        $user = $client->authLogin($code);
        return  MyResponse::success($user);
    }

    #[Route('POST','wechat/mpUserInfo')]
    public function mpUserInfo()
    {
        $iv = request()->param('iv','');
        $encryptedData = request()->param('encryptedData','');
        $code = request()->param('code','');
        $session_key =  request()->param('session_key','');
        if(empty($code)){
            return MyResponse::fail('code不能为空');
        }
        if(empty($iv)){
            return MyResponse::fail('iv不能为空');
        }
        if(empty($encryptedData)){
            return MyResponse::fail('encryptedData不能为空');
        }
        if(empty($session_key)){
            return MyResponse::fail('session_key不能为空');
        }

        $client = WechatClient::create();
        $res = $client->decryptData($iv,$session_key,$encryptedData);
        return MyResponse::success($res);
    }


//    public function decryptData($iv,$session_key,$encryptedData)
//    {
//        $config = config("mini_program");
//        if (strlen($session_key) != 24)return false;
//        if (strlen($iv) != 24)return false;
////        $encryptedData = str_replace(' ','+',$encryptedData);
////        $iv = str_replace(' ','+',$iv);
//
//        $aesKey=base64_decode($session_key);
//        $aesIV=base64_decode($iv);
//        $aesCipher=base64_decode($encryptedData);
//
//        $result=openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
//        $dataObj=json_decode($result);
//
//        if($dataObj == NULL)return false;
//        if($dataObj->watermark->appid != $config["app_id"])return false;
//        $data = get_object_vars($dataObj);
//        return $data;
//    }

    #[Route('GET','wechat/getMpToken')]
    public function getMpToken()
    {
        $client = WechatClient::create();
        $client->getAccessToken();
    }
}